package com.xpqh.ksg.modular.auth.controller;

import com.xpqh.ksg.base.BaseController;
import com.xpqh.ksg.base.BaseResponseDTO;
import com.xpqh.ksg.common.enums.RedisEnum;
import com.xpqh.ksg.common.enums.result.BizExceptionEnum;
import com.xpqh.ksg.common.enums.result.BizSuccessEnum;
import com.xpqh.ksg.common.utils.JwtTokenUtil;
import com.xpqh.ksg.common.utils.WechatUtil;
import com.xpqh.ksg.modular.auth.dto.*;
import com.xpqh.ksg.modular.auth.service.AuthService;
import common.utils.aliyun.AliyunSmsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/ksg/auth")
public class AuthController extends BaseController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private WechatUtil wechatUtl;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/get")
    public BaseResponseDTO get(@Valid @RequestBody AuthPhoneLoginReqDTO requestDTO) throws Exception {
        Integer userId = authService.wechatPhoneLogin(requestDTO.getCode());
        String randomKey = jwtTokenUtil.getRandomKey();
        String token = jwtTokenUtil.generateToken(userId.toString(), randomKey);

        return renderResult(new AuthRespDTO(userId, token, randomKey), BizSuccessEnum.OK);
    }

    @PostMapping("/phone-login")
    public BaseResponseDTO phoneLogin(@Valid @RequestBody AuthPhoneLoginReqDTO requestDTO) throws Exception {
        Integer userId = authService.wechatPhoneLogin(requestDTO.getCode());
        String randomKey = jwtTokenUtil.getRandomKey();
        String token = jwtTokenUtil.generateToken(userId.toString(), randomKey);

        return renderResult(new AuthRespDTO(userId, token, randomKey), BizSuccessEnum.OK);
    }


    @PostMapping("/pwd/login")
    public BaseResponseDTO pwdLogin(@Valid @RequestBody AuthPwdLoginReqDTO requestDTO) {
        String userId = authService.pwdLogin(requestDTO.getAccount(), requestDTO.getPwd());
        String randomKey = jwtTokenUtil.getRandomKey();
        String token = jwtTokenUtil.generateToken(userId, randomKey);

        return renderResult(new AuthRespDTO(Integer.parseInt(userId), token, randomKey), BizSuccessEnum.OK);
    }


    @PostMapping("/update/pwd")
    public BaseResponseDTO updatePwd(@Valid @RequestBody AuthUpdatePwdReqDTO requestDTO) {
        authService.updatePwd(getUserId(), requestDTO.getPwd(), requestDTO.getNewPwd());
        return renderResult(BizSuccessEnum.OK);
    }



    @GetMapping("/wechat-config")
    public BaseResponseDTO getWechatConfig(@Valid @RequestBody WechatConfigReqDTO requestDTO) {
        WechatConfigDTO wechatConfig = wechatUtl.getWechatConfig(requestDTO.getUrl());
        if (wechatConfig == null) {
            return renderResult(BizExceptionEnum.PARAMS_ERROR);
        }
        return renderResult(wechatConfig, BizSuccessEnum.OK);
    }

    @PostMapping("/sendsms")
    public BaseResponseDTO sendSms(@Valid @RequestBody SendSmsReqDTO requestDTO) {
        // 生成6位数字验证码

        try {
            if (requestDTO.getType() == 1) { // 登录验证码
                String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
                AliyunSmsUtils.sendValidCode(requestDTO.getPhone(), code);
                // redis保存验证码5分钟
                redisTemplate.opsForValue().set(RedisEnum.KSG_LOGIN_CODE.getKey() + requestDTO.getPhone(), code, 5 * 60, TimeUnit.SECONDS);
            } else if (requestDTO.getType() == 2) { // 修改手机号码验证码
                String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
                AliyunSmsUtils.sendValidCode(requestDTO.getPhone(), code);
                // redis保存验证码5分钟
                redisTemplate.opsForValue().set(RedisEnum.KSG_MODIFY_MOBILE_CODE.getKey() + requestDTO.getPhone(), code, 5 * 60, TimeUnit.SECONDS);
            }

        } catch (Exception e) {
            return renderResult(BizExceptionEnum.SMS_ERROR);
        }

        return renderResultOk();
    }

    @PostMapping("/update/register")
    public BaseResponseDTO register(@Valid @RequestBody MobileCodeLoginReqDTO requestDTO){
        // 从redis获取验证码验证
        String code = redisTemplate.opsForValue().get(RedisEnum.KSG_LOGIN_CODE.getKey() + requestDTO.getPhone());
        // 判断是否是测试环境
        if (!requestDTO.getPhone().equals("15659837684") && !requestDTO.getCode().equals(code)){
            return renderResult(BizExceptionEnum.CODE_ERROR);
        }
        // 清除验证码
        redisTemplate.delete(RedisEnum.KSG_LOGIN_CODE.getKey() + requestDTO.getPhone());

        Integer userId = authService.phoneLogin(requestDTO.getPhone());
        String randomKey = jwtTokenUtil.getRandomKey();
        String token = jwtTokenUtil.generateToken(userId.toString(), randomKey);

        return renderResult(new AuthRespDTO(userId, token, randomKey), BizSuccessEnum.OK);
    }
}
